package com.hsnn.medstgmini.settlement.dao.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.model.Whether;
import com.hsnn.medstgmini.settlement.dao.SettleAcctTransInfoDao;
import com.hsnn.medstgmini.settlement.model.SetAcctTransInfo;
import com.hsnn.medstgmini.settlement.model.TransType;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseNumber;

/**
 * @category 医疗机构交易明细Dao接口实现类
 * @author 韩守松
 * @date 2015年7月21日
 */
@Repository
public class SettleAcctTransInfoDaoImpl implements SettleAcctTransInfoDao {

	@Resource(name = "sessionFactory")
	private SessionFactory factory;

	/**
	 * @category 获取医疗机构交易明细数据
	 * @author 韩守松
	 * @date 2015年7月21日
	 * @param @param page
	 * @param @param acctTransInfo
	 * @param @param user
	 * @param @return
	 */
	public Pagination getBankAcctTransInfoList(Pagination page,
			SetAcctTransInfo acctTransInfo, SysUser user) {
		String orgId = "";
		if (user.getMain() == Whether.yes.getKey()) {
			orgId = user.getId();
		} else { // 非主帐号获取主帐号帐户信息
			orgId = user.getRootUser().getId();
		}
		acctTransInfo.setOrgId(orgId);
		return getBankAcctTransInfoList(page, acctTransInfo);
	}

	/**
	 * @category 根据帐户id查询银行卡列表
	 * @date 2015年7月21日
	 * @param page翻页参数
	 * @param bankAcct查询参数
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getBankAcctTransInfoList(Pagination page,
			SetAcctTransInfo acctTransInfo) {
		Session session = factory.getCurrentSession();
		StringBuffer listSb = new StringBuffer();
		listSb.append("SELECT a.trans_id transId, a.org_id orgId, a.trans_type transType, a.amount, a.trans_datetime transDateTime, a.outstand_amt outstandAmt, a.remark, a.upd_user updUser, b.name updUserName FROM set_accttransinfo a LEFT JOIN sys_user b ON a.upd_user = b.id WHERE a.org_id = :orgId ");

		Integer transType = acctTransInfo.getTransType();
		if (transType != null) {
			listSb.append("AND a.trans_type = :transType ");
		}
		Date staTime = acctTransInfo.getStaTime();
		if (staTime != null) {
			listSb.append("AND DATE_FORMAT(a.trans_datetime, '%Y-%m-%d') >= :staTime ");
		}
		Date endTime = acctTransInfo.getEndTime();
		if (endTime != null) {
			listSb.append("AND DATE_FORMAT(a.trans_datetime, '%Y-%m-%d') <= :endTime ");
		}
		
		listSb.append("ORDER BY a.trans_datetime DESC ");

		StringBuffer countSb = new StringBuffer();
		countSb.append("select count(*) from ( ");
		countSb.append(listSb.toString());
		countSb.append(") t ");

		SQLQuery countQuery = session.createSQLQuery(countSb.toString());
		SQLQuery listQuery = session.createSQLQuery(listSb.toString());

		countQuery.setString("orgId", acctTransInfo.getOrgId());
		listQuery.setString("orgId", acctTransInfo.getOrgId());

		if (transType != null) {
			countQuery.setInteger("transType", transType);
			listQuery.setInteger("transType", transType);
		}
		if (staTime != null) {
			countQuery.setString("staTime", DateUtil.date(staTime));
			listQuery.setString("staTime", DateUtil.date(staTime));
		}
		if (endTime != null) {
			countQuery.setString("endTime", DateUtil.date(endTime));
			listQuery.setString("endTime", DateUtil.date(endTime));
		}

		Long records = ((BigInteger) countQuery.uniqueResult()).longValue();
		page.setRecords(records);

		listQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		listQuery.setFirstResult(page.getFirstResult());
		listQuery.setMaxResults(page.getMaxResults());
		List<Map<String, Object>> list = listQuery.list();
		page.setRows(list);

		if (list != null && !list.isEmpty()) {
			for (Map<String, Object> map : list) {
				transType = Integer.valueOf((Byte) map.get("transType"));
				if (transType != null) {
					String transTypeName = TransType.getName(transType);
					map.put("transTypeName", transTypeName);
				}
				Date transDateTime = (Date) map.get("transDateTime");
				if (transDateTime != null) {
					map.put("transDateTime", DateUtil.dateTime(transDateTime));
				}
				BigDecimal amount = (BigDecimal) map.get("amount");
				if (amount != null) {
					map.put("amount",
							ParseNumber.toStrDecimal(amount.doubleValue()));
				}
				BigDecimal outstandAmt = (BigDecimal) map.get("outstandAmt");
				if (outstandAmt != null) {
					map.put("outstandAmt",
							ParseNumber.toStrDecimal(outstandAmt.doubleValue()));
				}
			}
		}

		return page;
	}
}